//
//  VipHelpViewController.m
//  AllFamily
//
//  Created by chirui on 2018/5/23.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "VipHelpViewController.h"
#import "HelpCollectionViewCell.h"
#import "MyCenterCollectionReusableView.h"
#import "PeopleListViewController.h"
#import "AddThirdCheckViewController.h"
#import "RuleDetailsViewController.h"

@interface VipHelpViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    
     UICollectionView * _collectionView;
    
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    
    UIButton * getBtn;
    UIButton * outBtn;
    
    UIView * lineView_one;
    UIView * lineView_two;
    
    NSString * typeStr;
    
    UIView * typeView;
    
     UIView * noBodyView;
}

@end

@implementation VipHelpViewController

-(void)viewWillDisappear:(BOOL)animated{
    
    typeView.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"互助帮扶");
    [self creatCollectionView];
    _page  =1;
    typeStr = @"display";
    _dataArray = @[].mutableCopy;
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_help_more" target:self action:@selector(creatHelp:)];
    
     noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-100, 200, 200) andMessageStr:@"还没有相关内容~" onView:nil];
    
    [self creatView];
    
     [self getMessageListDatafor:typeStr];
   
}

-(void)creatHelp:(UIButton *)btn{
    
    if (verifTokenAndEnter) {
         typeView.hidden = !typeView.hidden;
    }else{
        LoginAndSignUpVC * login = [[LoginAndSignUpVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        
    }
   
    
}

-(void)creatView {
     UIWindow *window = [[UIApplication sharedApplication].delegate window];
    typeView =[[UIView alloc]initWithFrame:CGRectMake(WIDTH-110,SH_NavBarHeight+10, 110, 100)];
    typeView.hidden =YES;
    
    
    UIImageView * image = [[UIImageView alloc]initWithFrame:CGRectMake(70, 0, 15, 10)];
    image.image = ImageName(@"icon_help_triangle");
    [typeView addSubview:image];
    
    UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, 110, 90)];
    
    bgView .backgroundColor  =[UIColor whiteColor];
    bgView.layer.cornerRadius = 5.f;
    bgView.layer.masksToBounds = YES;
    [typeView addSubview:bgView];
    
   UIButton * helpPeople = [UIButton buttonWithType:UIButtonTypeSystem];
    [self creatBtn:helpPeople Frame:CGRectMake(0, 10, 110, 40) andStr:@"健康值账户" andColor:ColorA(255, 255, 255, 0.5) andClick:@selector(helpPeopleClick:) onView:bgView];
   
     UIButton * applyHelp = [UIButton buttonWithType:UIButtonTypeSystem];
    [self creatBtn:applyHelp Frame:CGRectMake(0, 50, 110, 40) andStr:@"申请互助" andColor:[UIColor clearColor] andClick:@selector(applyHelpClick:) onView:bgView];
    
    [window addSubview:typeView];
    
}

-(void)helpPeopleClick:(UIButton *)btn{
    
    typeView.hidden = YES;
    PeopleListViewController * add = [[PeopleListViewController alloc]init];
    add.hidesBottomBarWhenPushed  = YES;
    self.navigationController.navigationBar.translucent=NO;
    [self.navigationController pushViewController:add animated:YES];
}

-(void)applyHelpClick:(UIButton *)btn{
     typeView.hidden = YES;
    AddThirdCheckViewController * add = [[AddThirdCheckViewController alloc]init];
    add.hidesBottomBarWhenPushed  = YES;
    self.navigationController.navigationBar.translucent=NO;
    [self.navigationController pushViewController:add animated:YES];
}


-(void)creatBtn:(UIButton *)btn Frame:(CGRect)crt andStr:(NSString *)str andColor:(UIColor *)col andClick:(SEL)click onView:(UIView *)view {
    
    btn.frame = crt;
    [btn setTitle:str forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.backgroundColor = col;
    btn.titleLabel.font =[UIFont systemFontOfSize:15];
    [btn addTarget:self action:click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
}

#pragma creatCollectionView

-(void)creatCollectionView {
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64+20) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        _page = 1;
        [self getMessageListDatafor:typeStr];
    }];
    _collectionView.mj_header = header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
       [self getMessageListDatafor:typeStr];
    }];
    
    footer.automaticallyRefresh = YES;
    _collectionView.mj_footer =footer;
    
    if (_dataArray.count>10) {
        _collectionView.mj_footer.hidden = NO;
    }else {
        
        _collectionView.mj_footer.hidden = YES;
    }
    
    
    //注册cell类
    [_collectionView registerNib:[UINib nibWithNibName:@"HelpCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HelpCollectionViewCell"];
    
    //    注册header类
    [_collectionView registerClass:[MyCenterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCenterCollectionReusableView"];
    
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
        NSDictionary * dic = _dataArray[indexPath.row];
    HelpCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HelpCollectionViewCell" forIndexPath:indexPath];
    cell.clipsToBounds = NO;
    
    UILabel *tagLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 20)];
    tagLabel.font =[UIFont systemFontOfSize:14];
    tagLabel.textAlignment = NSTextAlignmentCenter;
    if ([typeStr isEqualToString:@"display"]) {
        tagLabel.text =@"公示中";
        tagLabel.backgroundColor =  Color(58, 168, 38);
    }else {
        tagLabel.text =@"已互助";
        tagLabel.backgroundColor =  [UIColor lightGrayColor];
        
    }
    tagLabel.textColor =[UIColor whiteColor];
  
    [cell.userImage addSubview:tagLabel];
    [cell.userImage sd_setImageWithURL:ImageUrl(dic[@"cover_photo"]) placeholderImage:ImageName(@"img_new_default")];
        cell.detailsLabel.text = dic[@"title"];

    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    
    RuleDetailsViewController * rule = [[RuleDetailsViewController alloc]init];
    rule.hidesBottomBarWhenPushed = YES;
    rule.url = dic[@"web_url"];
    [self.navigationController pushViewController:rule animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    第一个参数是宽，第二个参数是高 5s  1.8   6 1.6   6p
    float height;
    if (ISP5||ISP4) {
        height = 1.5;
    }else if (ISP6){
        height = 1.3;
        
    }else if (ISP6P){
        height = 1.4;
    }else {
        
        height = 1.4;
    }
    
    CGSize size=CGSizeMake((WIDTH-30)/2, (WIDTH-30)/2*height);
    
    return size;
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //上 左 下 右
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置水平间隙   默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

////设置垂直间隙  默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(0,50);
}
//设置footer的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    //第一个参数：水平滑动时footer的宽度
    //第二个参数：垂直滑动时footer的高度
    return CGSizeMake(0, 0);
}

//kind:第二个参数:区分组头,组尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        MyCenterCollectionReusableView * view = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCenterCollectionReusableView" forIndexPath:indexPath];
        view.backgroundColor =[UIColor whiteColor];
        
        UIView * topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
        
        topView.backgroundColor =[UIColor whiteColor];
        [view addSubview:topView];
        
        lineView_one =[[UIView alloc]initWithFrame:CGRectMake(30, 48, WIDTH/2-60, 2)];
        lineView_one.backgroundColor = NavBackColor;
        lineView_one.hidden = YES;
        [topView addSubview:lineView_one];
        
        lineView_two =[[UIView alloc]initWithFrame:CGRectMake(WIDTH/2+30, 48, WIDTH/2-60, 2)];
        lineView_two.backgroundColor = NavBackColor;
        lineView_two.hidden = YES;
        [topView addSubview:lineView_two];
        
        getBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        getBtn.frame = CGRectMake(0, 0, WIDTH/2, 48);
        [getBtn setTitle:@"互助公示" forState:UIControlStateNormal];
        
        getBtn.titleLabel.font =[UIFont systemFontOfSize:16];
        [getBtn addTarget:self action:@selector(helpShow:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:getBtn];
        
        outBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        outBtn.frame = CGRectMake(WIDTH/2, 0, WIDTH/2, 48);
        [outBtn setTitle:@"互助记录" forState:UIControlStateNormal];
        if ([typeStr isEqualToString:@"display"]) {
            [getBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
            [outBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            lineView_one.hidden = NO;
            lineView_two.hidden = YES;
            
        }else {
            
            [outBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
            [getBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            lineView_one.hidden = YES;
            lineView_two.hidden = NO;
        }
        
        outBtn.titleLabel.font =[UIFont systemFontOfSize:16];
        [outBtn addTarget:self action:@selector(helpRecord:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:outBtn];
        
        return view;
        
    }else {
        
        return nil;
    }
}

-(void)helpShow:(UIButton *)btn{
    _page = 1;
    typeStr=@"display";
    [self getMessageListDatafor:typeStr];
//    [_collectionView reloadData];
}

-(void)helpRecord:(UIButton *)btn{
    _page = 1;
    typeStr=@"already";
    
//    [_collectionView reloadData];
    [self getMessageListDatafor:typeStr];
}

-(void)getMessageListDatafor:(NSString *)str{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_collectionView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"status":str
                           };
    
    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_helpList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"]  integerValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    noBodyView.hidden =YES;
                    if (_dataArray.count<10) {
                        
                        _collectionView.mj_footer.hidden = YES;
                    }else {
                        _collectionView.mj_footer.hidden = NO;
                    }
                }else {
                    _collectionView.mj_footer.hidden = YES;
                    noBodyView.hidden =NO;
                    
                    [self.view addSubview:noBodyView];
                }
                [_collectionView.mj_header endRefreshing];
                [_collectionView.mj_footer endRefreshing];
                [_collectionView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
    
}


@end
